package com.sophialex.health.record.common.util;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Text;

public class ControlsCascader {
	public static <T> void comboCascade(final Combo combo, final Control[] ctls, final String comboPath, final T value, final boolean enable) {
		combo.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				for(Control ctl : ctls) {
					triger(combo, ctl, comboPath, value, enable);
				}

			}
		});
		// 触发初始可用/不可用
		for(Control ctl : ctls) {
			triger(combo, ctl, comboPath, value, enable);
		}
	}

	public static <T> void comboCascade(final Combo combo, final Control[] ctls, String comboPath, T value) {
		comboCascade(combo, ctls, comboPath, value, true);
	}

	public static <T> void triger(final Combo combo, final Control ctl, final String comboPath, final T value, final boolean enable) {
		if(combo.getSelectionIndex() == -1) {
			ctl.setEnabled(!enable);
			return;
		}
		String s = combo.getItem(combo.getSelectionIndex());

		Object data = combo.getData(s);
		String[] dataPath = comboPath.split("\\.");
		String v = computeBeanPropValue(data, dataPath) + "";
		if(v.equals(value + "")) {
			ctl.setEnabled(enable);
		} else {
			if(ctl.getClass().equals(Text.class))
				((Text) ctl).setText("");
			ctl.setEnabled(!enable);
		}

	}

	private static Object computeBeanPropValue(Object bean, String[] beanPath) {
		if(beanPath.length == 1) {
			Object value = null;
			value = getFieldValue(bean, beanPath[0]);

			return value;
		} else {
			Object o = getFieldValue(bean, beanPath[0]);
			String[] newPath = new String[beanPath.length - 1];
			System.arraycopy(beanPath, 1, newPath, 0, beanPath.length - 1);
			return computeBeanPropValue(o, newPath);
		}
	}

	private static Object getFieldValue(Object o, String fieldName) {
		Object value = null;
		Field f = null;
		try {
			f = o.getClass().getDeclaredField(fieldName);
			f.setAccessible(true);
			try {
				value = f.get(o);
			}
			catch(Exception e) {
				e.printStackTrace();

			}

		}
		catch(Exception e) {
			// e.printStackTrace();
			// 若没有名为fieldName的字段，那尝试调用getter
			String name = "get" + Character.toUpperCase(fieldName.charAt(0)) + fieldName.substring(1);
			// parent.out(name + "\r\n");
			Method getter = null;
			try {
				getter = o.getClass().getMethod(name);
			}
			catch(Exception e1) {
				e1.printStackTrace();

			}
			try {
				value = getter.invoke(o);
			}
			catch(Exception e1) {
				e1.printStackTrace();

			}
			return value;
		}

		return value;
	}
}
